package ArrayList

import (
	"errors"
	"fmt"
)

//接口
type List interface {
	Size() int                                  //数组大小
	Get(index int) (interface{}, error)         //抓取第几个元素
	Set(index int, newval interface{}) error    //设置修改第几个元素的数据
	Insert(index int, newval interface{}) error //插入数据
	Append(newval interface{})                  //追加数据
	Clear()                                     //清空
	Delete(index int) error                     //删除
	String() string                             //返回字符串
	Iterator() Iterator                         //接口
}

// ArrayList 数据结构，字符串，数字
type ArrayList struct {
	dataStore []interface{} //数组存储
	TheSize   int           //数组的大小,首字母小写是私有自己用，大写是共有都可以用
}

//NewArrayList 开辟内存
func NewArrayList() *ArrayList {
	list := new(ArrayList)                      //初始化结构体
	list.dataStore = make([]interface{}, 0, 10) //开辟10个空间的内存
	list.TheSize = 0
	return list
}

//Size 接口实现：返回数组大小
func (list *ArrayList) Size() int {
	return list.TheSize
}

//接口实现：获取数组元素
func (list *ArrayList) Get(index int) (interface{}, error) {
	if index < 0 || index >= list.TheSize {
		return nil, errors.New("索引越界")
	}
	return list.dataStore[index], nil
}

func (list *ArrayList) Set(index int, newval interface{}) error {
	if index < 0 || index >= list.TheSize {
		return errors.New("索引越界")
	}
	list.dataStore[index] = newval //对数据设置
	return nil
}

//Insert 如果数组满了10个，新开辟内存
func (list *ArrayList) Insert(index int, newval interface{}) error {
	if index < 0 || index >= list.TheSize {
		return errors.New("索引越界")
	}
	list.checkisFull()                               //检测内存，如果满了自动追加
	list.dataStore = list.dataStore[:list.TheSize+1] //插入数据后，内存移动一位
	for i := list.TheSize; i > index; i-- {          //从后往前移动
		list.dataStore[i] = list.dataStore[i-1]
	}
	list.dataStore[index] = newval //插入数据
	list.TheSize++                 //索引追加
	return nil
}

func (list *ArrayList) checkisFull() {
	if list.TheSize == cap(list.dataStore) { // 判断内存使用
		//开辟双倍内存,第二个参数0=没有开辟内存
		newdataStore := make([]interface{}, 2*list.TheSize, 2*list.TheSize)
		copy(newdataStore, list.dataStore) //拷贝
		list.dataStore = newdataStore
	}
}

//接口实现：追加元素
func (list *ArrayList) Append(newval interface{}) {
	list.dataStore = append(list.dataStore, newval)
	list.TheSize++
}

func (list *ArrayList) Clear() {
	list.dataStore = make([]interface{}, 0, 10) //开辟10个空间的内存
	list.TheSize = 0
}

func (list *ArrayList) Delete(index int) error {
	//两个数组叠加到一起
	list.dataStore = append(list.dataStore[:index], list.dataStore[index+1:]...)
	list.TheSize--

	return nil
}

//接口实现：显示
func (list *ArrayList) String() string {
	return fmt.Sprint(list.dataStore)
}


